<?php
include_once("../includes/common.php");
include_once("../class/User.class.php");
include_once("../class/Action.class.php");
require_once("../islogin.php");

if ($islogin!=1){
    header('Location: /login.php');
    exit;
}

$menuavatar = !$user_info["message"]["avatar"] ? "/data/avatar/default.jpg" : $user_info["message"]["avatar"];

$setVparam = $_GET['type'] ?? '';
$allowedValues = [
    'like' => [
        'title' => '赞与收藏',
        'view' => 2
    ],
    'onlylike' => [
        'title' => '获赞详情',
        'view' => 3
    ],
    'onlystar' => [
        'title' => '收藏详情',
        'view' => 4
    ],
    'follow' => [
        'title' => '我的关注',
        'view' => 5
    ],
];

if (array_key_exists($setVparam, $allowedValues)) {
    $pageName = $allowedValues[$setVparam]['title']; // 根据 $get 设置标题
    $ulist_type = $allowedValues[$setVparam]['view']; // 获取对应的 view 值
}else{
    $pageName = '粉丝详情'; // 根据 $get 设置标题
    $ulist_type = 1;
}

if($ulist_type==5){
    $history_type = 10;     //我的关注
    $ulist_type = null;
}

if(!$pageName){
    exit('error pagename');
}

//初始化类处
$action = new Action();


//构造page
$nowPage = $_GET['page'] ?? 1;
if($nowPage<0){
    exit('page error');
}
$pageNum = 12;
$totalPage = 0;

// 获取当前 URL
$currentUrl = $_SERVER['REQUEST_URI'];
// 解析当前 URL
$parsedUrl = parse_url($currentUrl);
$queryParams = [];
if (isset($parsedUrl['query'])) {
    parse_str($parsedUrl['query'], $queryParams);
}

// 判断 $nowPage 是否为整数
if (!filter_var($nowPage, FILTER_VALIDATE_INT)||$nowPage==0) {
    exit(); // 如果不是整数，退出并显示消息
}
//浏览记录页面
if ($ulist_type==1){
    $ulist_info = json_decode($user->getUserFans($user_info['message']['user_id'],$nowPage,$pageNum),true);
    $totalPage = $user->getUserFansTotal($user_info['message']['user_id'],$pageNum);

}elseif ($ulist_type==2){
    $ulist_info = json_decode($action->getNotifyLike($user_info['message']['user_id'],$nowPage,$pageNum),true);
    $totalPage = $action->getNotifyLikeTotal($user_info['message']['user_id'],$pageNum);
    //var_dump($ulist_info);
}elseif ($ulist_type==3||$ulist_type==4){
    $ulist_info = json_decode($action->getNotifyLike($user_info['message']['user_id'],1,1000),true);
    $totalPage = 1;
    $pageNum = 1000;
    //4为收藏
    $searchKeyword = ($ulist_type == 4) ? 1 : 0;

    if ($_GET['so']) {
        $filteredResults = array_filter($ulist_info, function($item) use ($searchKeyword) {
            // 精准匹配 $item['check_result'] 是否等于 0，并且模糊匹配 $_GET['so'] 和 $item['title']
            return $item['action_type'] === (string)$searchKeyword && stripos($item['nickname'], $_GET['so']) !== false;
        });
    }else{
        $filteredResults = array_filter($ulist_info, function($item) use ($searchKeyword) {
            return $item['action_type'] === (string)$searchKeyword;
        });
    }



    $filteredResults = array_values($filteredResults);  //编制索引
    $ulist_info = $filteredResults;
    //var_dump($info_info);
    if(!$ulist_info){
        $ulist_info = array();
    }
}
if($history_type==10){
    $ulist_info = json_decode($user->getUserFollow($user_info['message']['user_id'],$nowPage,$pageNum),true);
    $totalPage = $user->getUserFollowTotal($user_info['message']['user_id'],$pageNum);
    //var_dump($ulist_info);

}

if($_GET['so']){
    $totalPage = 1;
    $searchKeyword = $_GET['so'] ?? ''; // 获取搜索关键词
    $pageNum = 1000;

    if($ulist_type==1){
        $sodataArray = json_decode($user->getUserFans($user_info['message']['user_id'],1,1000),true);

        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            return stripos($item['nickname'], $searchKeyword) !== false; // 不区分大小写的模糊匹配
        });

    }

    if($ulist_type==2||$history_type==10){
        if($history_type==10){
            $sodataArray = json_decode($user->getUserFollow($user_info['message']['user_id'],1,1000),true);
        }else{
            $sodataArray = json_decode($action->getNotifyLike($user_info['message']['user_id'],1,1000),true);
        }
        //var_dump($sodataArray);
        $filteredResults = array_filter($sodataArray, function($item) use ($searchKeyword) {
            return stripos($item['nickname'], $searchKeyword) !== false; // 不区分大小写的模糊匹配
        });
    }


    $filteredResults = array_values($filteredResults);  //编制索引

    if($ulist_info){
        $ulist_info = $filteredResults;
    }


}


if(!$ulist_info){
    $ulist_info = [];
}

function calculateAge($birthday) {
    if ($birthday==null){
        return '未知';
    }
    $birthDate = new DateTime($birthday);
    $currentDate = new DateTime();
    $age = $currentDate->diff($birthDate)->y;
    return $age;
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <?php require_once('head.php'); ?>
</head> 
<body>
    
<!--==================== Preloader Start ====================-->
  <div class="preloader">
    <div class="loader"></div>
  </div>
<!--==================== Preloader End ====================-->

<!--==================== Sidebar Overlay End ====================-->
<div class="side-overlay"></div>
<!--==================== Sidebar Overlay End ====================-->

<?php require_once('user_menu.php'); ?>
    <div class="dashboard-main-wrapper">
        <?php require_once('top_navbar.php'); ?>
        <div class="dashboard-body">

            <div class="breadcrumb-with-buttons mb-24 flex-between flex-wrap gap-8">


                <!-- Breadcrumb Right Start -->
                <div class="flex-align gap-8 flex-wrap">
                    <?php if ($ulist_type!=1){?>
                    <div class="position-relative text-gray-500 flex-align gap-4 text-13">
                        <span class="text-inherit">筛选: </span>
                        <div class="flex-align text-gray-500 text-13 border border-gray-100 rounded-4 ps-20 focus-border-main-600 bg-white">
                            <span class="text-lg"><i class="ph ph-funnel-simple"></i></span>
                            <select onchange="handleChange(this)" class="form-control ps-8 pe-20 py-16 border-0 text-inherit rounded-4 text-center">
                                <option value="2" <?php echo $ulist_type==2 ? 'selected':'';?>>点赞与收藏</option>
                                <option value="3" <?php echo $ulist_type==3 ? 'selected':'';?>>只看点赞</option>
                                <option value="4" <?php echo $ulist_type==4 ? 'selected':'';?>>只看收藏</option>
                            </select>
                        </div>
                    </div>
                    <?php }?>
                    <div class="flex-align text-gray-500 text-13 border border-gray-100 rounded-4 ps-20 focus-border-main-600 bg-white">
                        <span class="text-lg"><i class="ph ph-layout"></i></span>
                        <select class="form-control ps-8 pe-20 py-16 border-0 text-inherit rounded-4 text-center" id="exportOptions">
                            <option value="" selected disabled>导出</option>
                            <option value="csv">CSV</option>
                            <option value="json">JSON</option>
                        </select>
                    </div>
                </div>
                <!-- Breadcrumb Right End -->
            </div>
           

            <div class="card overflow-hidden">
                <div class="card-body p-0 overflow-x-auto">
                    <table id="studentTable" class="table table-striped">
                        <thead>
                            <tr>
                                <th class="fixed-width">
                                    <div class="form-check">
                                        <input class="form-check-input border-gray-200 rounded-4" type="checkbox" id="selectAll">
                                    </div>
                                </th>
                                    <th class="h6 text-gray-300">头像/昵称</th>
                                    <th class="h6 text-gray-300"><?php echo ($ulist_type == 1||$history_type==10) ? '小蓝书号' : '笔记标题'; ?></th>
                                    <?php echo ($ulist_type == 1||$history_type==10) ? '<th class="h6 text-gray-300">年龄</th>' : '<th class="h6 text-gray-300">操作类型</th>'; ?>
                                <?php echo ($history_type==10) ? '<th class="h6 text-gray-300">用户属地</th>' : '<th class="h6 text-gray-300">地点</th>'; ?>
                                    <th class="h6 text-gray-300">性别</th>
                                    <th class="h6 text-gray-300"><?php echo ($ulist_type == 1) ? '关注' : '操作'; ?>时间</th>
                                    <?php echo ($ulist_type == 1) ? '<th class="h6 text-gray-300">主页</th>' : ''; ?>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($ulist_type==1){?>
                            <?php for ($i = 0; $i < count($ulist_info); $i++) { ?>
                                <tr>
                                    <td class="fixed-width">
                                        <div class="form-check">
                                            <input class="form-check-input border-gray-200 rounded-4" type="checkbox">
                                        </div>
                                    </td>
                                    <td>
                                        <div class="flex-align gap-8">
                                            <img src="<?php echo '/' . ltrim($ulist_info[$i]["avatar"] ?: '/data/avatar/default.jpg', '/'); ?>" alt="" class="w-40 h-40 rounded-circle">
                                            <span class="h6 mb-0 fw-medium text-gray-300"><?php echo $ulist_info[$i]['nickname'];?></span>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="h6 mb-0 fw-medium text-gray-300"><?php echo $ulist_info[$i]['blue_id'];?></span>
                                    </td>
                                    <td>
                                        <span class="h6 mb-0 fw-medium text-gray-300"><?php echo calculateAge($ulist_info[$i]['birthday']);?> 岁</span>
                                    </td>
                                    <td>
                                        <span class="h6 mb-0 fw-medium text-gray-300"><?php echo getIpProvince($ulist_info[$i]['ip'])?></span>
                                    </td>
                                    <td>
                                    <span class="text-13 py-2 px-8
                                        <?php echo $ulist_info[$i]['gender'] == 0 ? 'bg-pink text-pink-600' : 'bg-main text-main-600'; ?>
                                        d-inline-flex align-items-center gap-8 rounded-pill">

                                        <span class="w-6 h-6
                                            <?php echo $ulist_info[$i]['gender'] == 0 ? 'bg-pink-600' : 'bg-main-600'; ?>
                                            rounded-circle flex-shrink-0"></span>

                                        <?php
                                        if ($ulist_info[$i]['gender'] == 1) {
                                            echo '男';
                                        }elseif ($ulist_info[$i]['gender'] == '0') {
                                            echo '女';
                                        }else{
                                            echo '未知';
                                        }
                                        ?>


                                    </span>
                                    </td>
                                    <td>
                                        <span class="h6 mb-0 fw-medium text-gray-300"><?php echo formatNoteTime($ulist_info[$i]['fans_time'])?></span>
                                    </td>
                                    <td>
                                        <a href="/profile.php?id=<?php echo $ulist_info[$i]['fans_id'];?>" class="bg-main-50 text-main-600 py-2 px-14 rounded-pill hover-bg-main-600 hover-text-white">查看</a>
                                    </td>
                                </tr>
                            <?php } ?>
                        <?php }else{?>
                            <?php for ($i = 0; $i < count($ulist_info); $i++) { ?>
                                <tr>
                                    <td class="fixed-width">
                                        <div class="form-check">
                                            <input class="form-check-input border-gray-200 rounded-4" type="checkbox">
                                        </div>
                                    </td>
                                    <td>
                                        <div class="flex-align gap-8">
                                            <img style="cursor: pointer" onclick="window.location.href='/profile.php?id=<?php echo $ulist_info[$i]["user_id"];?>'" src="<?php echo '/' . ltrim($ulist_info[$i]["avatar"] ?: '/data/avatar/default.jpg', '/'); ?>" alt="" class="w-40 h-40 rounded-circle">
                                            <span style="cursor: pointer" onclick="window.location.href='/profile.php?id=<?php echo $ulist_info[$i]["user_id"];?>'" class="h6 mb-0 fw-medium text-gray-300"><?php echo $ulist_info[$i]['nickname'];?></span>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if($history_type==10){?>
                                            <span style="cursor: pointer" onclick="window.location.href='/profile.php?id=<?php echo $ulist_info[$i]["user_id"];?>'" class="h6 mb-0 fw-medium text-gray-300"><?php echo $ulist_info[$i]["blue_id"];?></span>
                                        <?php }else{?>
                                            <span style="cursor: pointer" onclick="window.location.href='/explore.php?id=<?php echo $ulist_info[$i]["note_id"];?>'" class="h6 mb-0 fw-medium text-gray-300">《<?php echo $ulist_info[$i]["title"];?>》</span>
                                        <?php }?>
                                    </td>
                                    <td>

                                        <?php if($history_type==10){?>
                                            <span class="h6 mb-0 fw-medium text-gray-300"><?php echo calculateAge($ulist_info[$i]["birthday"]);?> 岁</span>
                                        <?php }else{?>
                                            <span class="h6 mb-0 fw-medium <?php echo $ulist_info[$i]["action_type"] ? "text-warning-600" : "text-pink-600"?>"><?php echo $ulist_info[$i]["action_type"] ? "<i class=\"ph-fill ph-star\"></i>收藏" : "<i class=\"ph-fill ph-heart\"></i>点赞";?></span>
                                        <?php }?>
                                    </td>
                                    <td>
                                        <span class="h6 mb-0 fw-medium text-gray-300"><?php echo getIpProvince($ulist_info[$i]['ip'])?></span>
                                    </td>
                                    <td>
                                    <span class="text-13 py-2 px-8
                                        <?php echo $ulist_info[$i]['gender'] == 0 ? 'bg-pink text-pink-600' : 'bg-main text-main-600'; ?>
                                        d-inline-flex align-items-center gap-8 rounded-pill">

                                        <span class="w-6 h-6
                                            <?php echo $ulist_info[$i]['gender'] == 0 ? 'bg-pink-600' : 'bg-main-600'; ?>
                                            rounded-circle flex-shrink-0"></span>

                                        <?php
                                        if ($ulist_info[$i]['gender'] == 1) {
                                            echo '男';
                                        }elseif ($ulist_info[$i]['gender'] == '0') {
                                            echo '女';
                                        }else{
                                            echo '未知';
                                        }
                                        ?>


                                    </span>
                                    </td>
                                    <td>

                                        <?php if($history_type==10){?>
                                            <span class="h6 mb-0 fw-medium text-gray-300"><?php echo formatNoteTime($ulist_info[$i]["fans_time"])?></span>
                                        <?php }else{?>
                                            <span class="h6 mb-0 fw-medium text-gray-300"><?php echo formatNoteTime($ulist_info[$i]["action_time"])?></span>
                                        <?php }?>
                                    </td>
                                </tr>
                            <?php } ?>
                        <?php }?>



                        </tbody>
                    </table>
                </div>
                <div class="card-footer flex-between flex-wrap">
                    <span class="text-gray-900">1-<?php echo $totalPage?> 页 每页 <?php echo $pageNum?> 条</span>
                    <ul class="pagination flex-align flex-wrap">
                        <?php if($totalPage>1){?>
                                <?php include 'pagination.php'; ?>
                        <?php }?>
                    </ul>
                </div>
            </div>
            
        </div>
        <?php require_once('footer.php'); ?>
    </div>


<?php require_once('foot.php'); ?>


    <script>
        function handleChange(select) {
            if (select.value == 2) {
                window.location.href = '/control/userlist.php?type=like';
            }
            if (select.value == 3) {
                window.location.href = '/control/userlist.php?type=onlylike';
            }
            if (select.value == 4) {
                window.location.href = '/control/userlist.php?type=onlystar';
            }
        }
        // ========================== Export Js Start ==============================
        document.getElementById('exportOptions').addEventListener('change', function() {
            const format = this.value;
            const table = document.getElementById('studentTable');
            let data = [];
            const headers = [];
            
            // Get the table headers
            table.querySelectorAll('thead th').forEach(th => {
                headers.push(th.innerText.trim());
            });

            // Get the table rows
            table.querySelectorAll('tbody tr').forEach(tr => {
                const row = {};
                tr.querySelectorAll('td').forEach((td, index) => {
                    row[headers[index]] = td.innerText.trim();
                });
                data.push(row);
            });

            if (format === 'csv') {
                downloadCSV(data);
            } else if (format === 'json') {
                downloadJSON(data);
            }
        });

        function downloadCSV(data) {
            const csv = data.map(row => Object.values(row).join(',')).join('\n');
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'info.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }

        function downloadJSON(data) {
            const json = JSON.stringify(data, null, 2);
            const blob = new Blob([json], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'info.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
        // ========================== Export Js End ==============================
    
        // Table Header Checkbox checked all js Start
        $('#selectAll').on('change', function () {
            $('.form-check .form-check-input').prop('checked', $(this).prop('checked')); 
        }); 
    
        // Data Tables
        new DataTable('#studentTable', {
            searching: false,
            lengthChange: false,
            info: false,   // Bottom Left Text => Showing 1 to 10 of 12 entries
            paging: false, // Pagination False
            "columnDefs": [
                { "orderable": false, "targets": [0, 6] } // Disables sorting on the 7th column (index 6)
            ]
        });
    </script>

    </body>
</html>